package yxy.game.pm2.command.arena;

import yxy.cherry.data.bean.arenadate;
import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ArenaMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.arena.ArenaHandle;
import yxy.game.pm2.module.arena.ArenaPlayerModule;

/** 竞技场 购买挑战次数 */
@MessageType(proto = Command.ArenaChanllengePurchase, classtype = ArenaMessage.ArenaChanllengePurchaseRequest.class)
public class CMD_ArenaChanllengePurchase extends Command<ArenaMessage.ArenaChanllengePurchaseRequest> {

	@Override
	public void execute(MessageSource messageSource, ArenaMessage.ArenaChanllengePurchaseRequest request) {
		String playerCode = messageSource.getTag();
		int times = request.getItemNum();

		ArenaMessage.ArenaChanllengePurchaseResponse.Builder response = ArenaMessage.ArenaChanllengePurchaseResponse.newBuilder();

		if (times > 1000 || times <= 0) {
			send(messageSource, response, Result.ParamError);// 数据不对
			return;
		}

		ArenaPlayerModule module = ArenaPlayerModule.get(playerCode);
		if (module == null) {
			send(messageSource, response, Result.ModuleNotOpen);// 竞技场模块没有开启
			return;
		}

		try {
			if (module.tryLock()) {
				int price = fomula.竞技场花费元宝购买挑战道具价格.intValue();
				Currency cost = Currency.create(CurrencyType.CT_元宝, 0, price * times);
				try {
					new CurrencyHandle().cost(playerCode, CCReason.竞技场, cost);
				} catch (CurrencyNotEnoughException e) {
					send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
					return;
				}

				arenadate data = new ArenaHandle().data(0);
				new CurrencyHandle().addCurrency(playerCode, CCReason.竞技场, Currency.create(data.getCosttype(), data.getCostid(), times));
				long costNumber = Currency.number(playerCode, CurrencyType.forNumber(data.getCosttype()), data.getCostid(),false);

				response.setItemNum(costNumber);

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			module.unlock();
		}
	}

	private void send(MessageSource messageSource, ArenaMessage.ArenaChanllengePurchaseResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}